package cn.com.surker.pages;

import cn.com.surker.cache.MemoryCache;
import cn.com.surker.common.AESCoder;
import cn.com.surker.common.AbstractController;
import cn.com.surker.common.Constant;
import cn.com.surker.common.CookiesUtil;
import cn.com.surker.enums.ICodeDescEnum;
import cn.com.surker.enums.production.indent.IsProEnum;
import cn.com.surker.enums.production.indent.ProTypeEnum;
import cn.com.surker.enums.system.StationEnum;
import cn.com.surker.enums.weight.OrderWeightTypeEnum;
import cn.com.surker.enums.weight.WeightCarTypeEnum;
import cn.com.surker.oauth.AuthUtils;
import cn.com.surker.redis.RedisUtils;
import cn.com.surker.spring.RestResultDto;
import cn.com.surker.system.entity.SysUser;
import cn.com.surker.system.model.CacheUser;
import cn.com.surker.system.service.*;
import cn.com.surker.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 * @Author lucky
 * @create 2021年02月21 23:43
 * @desc
 */
@Slf4j
@Controller
@RequestMapping("/console")
public class ConsoleIndexController extends AbstractController {

    @Value("${erp.datasource.erp.db}")
    private String dbCode;
    @Value("${erp.datasource.org.name}")
    protected String orgName;
    @Value("${erp.domain}")
    protected String domain;
    @Value("${erp.agentId}")
    protected String agentId;
    /**用户业务类**/
    @Resource
    private UserService userService;
    /**菜单业务类**/
    @Resource
    private MenuInfoService menuInfoService;
    @Resource
    private RoleService roleService;
    /**部门业务类**/
    @Resource
    private OriginService originService;
    @Autowired
    private RedisUtils redisUtils;
    @Resource
    private StationLogService logService;

    @RequestMapping("/panel")
    public ModelAndView panel() {
        CacheUser user = getUser();
        ModelAndView mode = new ModelAndView();
//        if (user == null) {
//            mode.setViewName("console/system/panel");
//            return mode;
//        }
//        Long time = new Date().getTime();
//        String echostr = AESCoder.encrypt("oa" + "_" + user.getUsername() + "_" + time, Constant.centerSecret);
//        mode.addObject("isDataCheck", isDataCheck);
//        mode.addObject("username", user.getUsername());
//        mode.addObject("oauthType", "oa");
//        mode.addObject("timestamp", time);
//        mode.addObject("echostr", echostr);
//        mode.addObject("token", AESCoder.encrypt(user.getToken(), Constant.CACHE_USER));
        List<Map<String, Object>> isProList = ICodeDescEnum.getEnumDatasV1(IsProEnum.class);
        List<Map<String, Object>> proTypeList = ICodeDescEnum.getEnumDatasV1(ProTypeEnum.class);
        List<Map<String, Object>> carTypeList = ICodeDescEnum.getEnumDatasV1(WeightCarTypeEnum.class);
        List<Map<String, Object>> weightTypeList = ICodeDescEnum.getEnumDatasV1(OrderWeightTypeEnum.class);

        mode.addObject("isProList", isProList);
        mode.addObject("proTypeList", proTypeList);
        mode.addObject("carTypeList", carTypeList);
        mode.addObject("weightTypeList", weightTypeList);
        mode.addObject("name", user.getName());
        mode.setViewName("console/system/panel");
        return mode;
    }

    /**
     * 登录页面
     * @return
     */
    @RequestMapping("/login")
    public ModelAndView login(String type, String code) {
        ModelAndView mode = new ModelAndView();
//        if (StringUtils.isNull(dbCode))
//            dbCode = "CX_BBYBN";
        String url = domain;
        String agentId_ = agentId;
        mode.addObject("redirectUri", url);
        mode.addObject("agentId", agentId);
        mode.addObject("orgName", orgName);
        mode.setViewName("console/system/login");

        return mode;
//        log.error("code:{},type:{}", code, type);
//        if (StringUtils.isNull(type) || !type.equals("jssdk")) {
//            return "console/system/login";
//        } else {
//            String username = WechatApi.getUserId(code);
//            log.error("企业微信授权登录码:{},微信登录用户名:{}", code, username);
//            SysUser user = serviceImpl.wechatLogin(username);
//            if (user != null) {
//                CacheUser cacheUser = new CacheUser(user);
//                cacheUser.setRoleList(roleService.loadUserMenu(user.getId()));
//                /**加密令牌**/
//                String appToken = AuthUtils.createToken(cacheUser.getId() + new Date().getTime());
//                cacheUser.setToken(appToken);
//                redisUtils.set(appToken, cacheUser, 14400L);
//                AbstractController.setUserCookie(cacheUser);
//                return "console/system/index";
//            }
//            return "console/system/login";
//        }
    }

    /**
     * 角色页面
     * @return
     */
    @RequestMapping("/role")
    public String role() {
        Boolean verify = isVerify("/console/role");
        if (verify)
            return "console/system/role";
        else
            return "error/403";
    }

    /**
     * 首页
     * @return
     */
    @RequestMapping("/index")
    public ModelAndView index() {
        CacheUser user = getUser();
        ModelAndView mode = new ModelAndView();
        if (user == null) {
//            if (StringUtils.isNull(dbCode))
//                dbCode = "CX_BBYBN";
            String url = Constant.erpUrlMap.get(dbCode);
            mode.addObject("redirectUri", url);
            mode.setViewName("console/system/login");
            return mode;
        }
//        Long time = new Date().getTime();
//        String echostr = AESCoder.encrypt("oa" + "_" + user.getUsername() + "_" + time, Constant.centerSecret);
//        mode.addObject("isDataCheck", isDataCheck);
//        mode.addObject("username", user.getUsername());
//        mode.addObject("oauthType", "oa");
//        mode.addObject("timestamp", time);
//        mode.addObject("echostr", echostr);
//        mode.addObject("token", AESCoder.encrypt(user.getToken(), Constant.CACHE_USER));
        mode.setViewName("console/system/index");
        mode.addObject("name", user.getName());
        mode.addObject("orgName", orgName);
        return mode;
    }

    /**
     * 用户管理页面
     * @return
     */
    @RequestMapping("/user")
    public String user() {
        Boolean verify = isVerify("/console/user");
        if (verify)
            return "console/system/user";
        else
            return "console/system/user";
    }

    /**
     * 按钮管理页面
     * @return
     */
    @RequestMapping("/button")
    public String button() {
        Boolean verify = isVerify("/console/button");
        if (verify)
            return "console/system/button";
        else
            return "error/403";
    }

    /**
     * 菜单管理页面
     * @return
     */
    @RequestMapping("/menu")
    public String menu() {
        Boolean verify = isVerify("/console/menu");
        if (verify)
            return "console/system/menu";
        else
            return "error/403";
    }

    /**
     * 部门管理页面
     * @return
     */
    @RequestMapping("/origin")
    public String origin () {
        Boolean verify = isVerify("/console/origin");
        if (verify)
            return "console/system/origin";
        else
            return "error/403";
    }

    /**
     * 加载菜单
     * @return
     */
    @RequestMapping(value = "/load/menu", method = RequestMethod.POST)
    @ResponseBody
    public RestResultDto loadMenu(Integer isDataCheck) {
        try {
            CacheUser cacheUser = getUser();
            List<Map<String, Object>> list;
//            if (cacheUser.getUsername().equals("admin") || cacheUser.getUsername().equals("lucky")) {
//                list = menuInfoService.loadUserMenuV1(cacheUser.getId(), 1, 1);
//            } else {
////                if (StringUtils.isNull(isDataCheck))
////                    isDataCheck = 0;
////                list = menuInfoService.loadUserMenuV1(cacheUser.getId(), isDataCheck, 1);
//                list = menuInfoService.loadUserMenu(cacheUser.getId(), null, 1);
//            }
            list = menuInfoService.loadUserMenuV1(cacheUser.getId(), 1, 1);


            if (list == null || list.size() == 0)
                return RestResultDto.fail("未获取任何数据");
            return RestResultDto.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResultDto.fail("数据加载异常");
        }
    }


    /**
     * 站点选择
     * @param originId
     * @return
     */
    @RequestMapping(value = "/chose/station",method = RequestMethod.POST)
    @ResponseBody
    public RestResultDto choseStation(Long originId, HttpServletRequest request) {
        try {
            CacheUser user = getUser();
            if (user == null)
                return RestResultDto.fail("请先登录后在选择站点");

            user = originService.choseStation(user.getToken(), originId,
                    user.getId(), StationEnum.MIXING.getCode(), IpUtils.getIpAddress(request));
            return RestResultDto.success(user);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResultDto.fail("系统异常,数据加载失败");
        }
    }

    /**
     *  登录后验证是否选择站点
     **/
    @RequestMapping(value = "/check/station",method = RequestMethod.POST)
    @ResponseBody
    public RestResultDto checkStation(HttpServletRequest request) {
        try {
            /**获取登录token**/
            String token = StringUtils.convertString(request.getSession().getAttribute("erp_oauth_token"));

            CacheUser cacheUser = (CacheUser) redisUtils.get(token);
            if (cacheUser.getDataSourceInfo() == null )
                return RestResultDto.fail("请选择站点");
            else
                return RestResultDto.success(cacheUser);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResultDto.fail("系统异常,数据加载失败");
        }
    }


    /**
     *  登录验证
     * @param username 登录账号
     * @param password 登录密码
     **/
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public RestResultDto login(@RequestParam("username")String username,
                               @RequestParam("password")String password,
                               @RequestParam("verifyCode") String verifyCode,String openid,
                               String avatarUrl, String nickName,
                               HttpServletRequest request){
        try {
            /**获取缓存中的验证码**/
            String code  = (String) request.getSession().getAttribute("verifyCode");
            if (StringUtils.isNull(verifyCode) || StringUtils.isNull(code))
                return new RestResultDto(RestResultDto.FAIL_AUTH, "请输入验证码");

            if (!verifyCode.toLowerCase().equals(code.toLowerCase()))
                return new RestResultDto(RestResultDto.FAIL_AUTH, "验证码错误");
            if (StringUtils.isNull(username))
                return RestResultDto.fail("用户名为空");
            if (StringUtils.isNull(password))
                return RestResultDto.fail("密码为空");

            System.out.println(userService);
            SysUser user = userService.queryUser(username);
            if (user == null)
                return RestResultDto.fail("用户不存在");

            /**加密密码**/
            String pwd = AESCoder.md5(password);
            if (StringUtils.isNull(user.getPassword()) || !pwd.equals(user.getPassword()))
                return RestResultDto.fail("登录密码错误");

            if (!StringUtils.isNull(openid) || !StringUtils.isNull(avatarUrl)
                    || !StringUtils.isNull(nickName)) {
                if (!StringUtils.isNull(openid))
                    user.setOpenid(openid);
                if (!StringUtils.isNull(nickName))
                    user.setNickname(nickName);
                if (!StringUtils.isNull(avatarUrl))
                    user.setAvatarUrl(avatarUrl);
                userService.update(user);
            }

            CacheUser cacheUser = new CacheUser(user);
            cacheUser.setRoleList(roleService.loadUserMenu(user.getId()));
            cacheUser.setRoleNameList(roleService.loadRoleName(cacheUser.getId()));
            cacheUser.setIp(IpUtils.getIpAddress(request));
            cacheUser = logService.save(cacheUser);
            /**加密令牌**/
            String appToken = AuthUtils.createToken(cacheUser.getId() + new Date().getTime());
            cacheUser.setToken(appToken);
            redisUtils.set(appToken, cacheUser, 7200L);
            AbstractController.setUserCookie(cacheUser);
            return RestResultDto.success("登录成功", cacheUser);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResultDto.fail("系统异常,登录失败");
        }
    }

    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public RestResultDto logout(HttpServletRequest request, HttpServletResponse response) {
        try {
            /**获取登录token**/
            String token = StringUtils.convertString(request.getSession().getAttribute("erp_oauth_token"));

            if (!StringUtils.isNull(token)) {
                redisUtils.remove(token);
                request.getSession().removeAttribute("erp_oauth_token");
            }

            /**cookie缓存KEY**/
            String secretKey = Constant.COOKIE_KEY;
            /**清楚Cookie**/
            CookiesUtil.removeCookies(secretKey, response);
            return RestResultDto.success("退出登录");
        } catch (Exception e) {
            e.printStackTrace();
            return RestResultDto.fail("系统异常,数据加载失败");
        }
    }


    /**
     * 生成验证码
     */
    @RequestMapping(value = "/auth/code")
    public void authCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        /**生成随机字串**/
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        String type = request.getParameter("type");
        /**h5端验证码**/
        if (!StringUtils.isNull(type) && StringUtils.convertInteger(type) == 1) {
            /**存入会话session**/
            HttpSession session = request.getSession(true);
            /**删除以前的**/
            session.removeAttribute("verifyCode");
            session.setAttribute("verifyCode", verifyCode.toLowerCase());
        } else if (!StringUtils.isNull(type) && StringUtils.convertInteger(type) == 2) {
            /**设备ID编号**/
            String deviceId = request.getParameter("deviceId");
            if (!StringUtils.isNull(deviceId)) {
                MemoryCache memoryCache = MemoryCache.getInstance();
                if (memoryCache.get(deviceId) != null)
                    memoryCache.remove(deviceId);
                memoryCache.set(deviceId, verifyCode.toLowerCase(), 600000);
            }
        }

        //生成图片
        int w = 150, h = 50;
        VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);
    }


}
